from django.shortcuts import render
from rest_framework.response import Response

# Create your views here.

from rest_framework.viewsets import ModelViewSet

from BugManage.models import BugManage, BugHandle
from BugManage.serializers import BugManageSerializer, BugManageListSerializer
from rest_framework import permissions


class BugView(ModelViewSet):
    queryset = BugManage.objects.all()
    serializer_class = BugManageSerializer
    permission_classes = [permissions.IsAuthenticated]

    def create(self, request, *args, **kwargs):
        obj = super().create(request, *args, **kwargs)
        bug = BugManage.objects.get(id=obj.data.get("id"))
        handle_info = obj.data.get("status")
        BugHandle.objects.create(bug=bug, handle=handle_info, update_user=request.user.username)
        return obj

    def update(self, request, *args, **kwargs):
        obj = super().update(request, *args, **kwargs)
        bug = BugManage.objects.get(id=obj.data.get("id"))
        handle_info = obj.data.get("status")
        BugHandle.objects.update(bug=bug, handle=handle_info, update_user=request.user.username)
        return obj

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = BugManageListSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = BugManageListSerializer(queryset, many=True)
        return Response(serializer.data)
